<template>
    <div class="layout-content">
        <div class="layout-content-main">
            <Breadcrumb class="content-title mbt1">
                <BreadcrumbItem>自定义角色</BreadcrumbItem>
            </Breadcrumb>
            <div class="section">
                <div class="section-title">
                    自定义角色
                </div>
                <Row class="mbt4">
                    <Col span="6">
                    <Input v-model="searchValue" placeholder="请输入角色名称">

                        <Button slot="append" icon="ios-search" @click="searchRole()"></Button>
                    </Input>
                    </Col>

                    <Col span="18" class="text-right">
                    <Button type="primary" size="large" @click="createRoleModal=true">创建角色</Button>
                    </Col>
                </Row>
                <Table border :columns="columns7" :data="selfDefinedRoleList" class="mbt4"></Table>
                <Page :total="selfDefinedRoleListNum" show-total class="center" @on-change="changePage" :page-size='9'></Page>
                <!-- 创建基角色start -->
               <Modal v-model="createRoleModal" class="small-modal" title="创建角色名称">
                    
                    <Form ref="newRole" :model="newRole" :rules="ruleValidate" :label-width="80">
                        <FormItem label="角色名称" prop="roleName">
                            <Input v-model="newRole.roleName" size="large" placeholder="角色名称"></Input>
                        </FormItem>

                        <FormItem label="排序">
                          <Select v-model="newRole.sort">
                              <Option :key="item" :value="item" v-for="item in sortList">{{item}}</Option>
                              
                          </Select>
                        </FormItem>
                      
                    </Form>
                    <div slot="footer">
                      <Button @click="createRoleModal=false">取消</Button>
                      <Button type="primary" @click="saveRole('newRole')">保存</Button>
                    </div>
                </Modal>
                <!-- 创建基角色end-->

                <!-- 选择权限的弹出框start -->
               <Modal v-model="chooseJurisdictionModal" class="small-modal" title="选择权限">
            
                        <el-tree                           
                                                      
                            :data="jurisdictionTreeData"                         
                            :props="defaultProps"                               
                            node-key="functionId"                                                                                                                 
                            :expand-on-click-node="false"  
                            :check-strictly="true"                                                                                                          
                            show-checkbox
                            ref="tree" style="border:none">
                        </el-tree>
          
                      <div slot="footer">
                          <Button @click="chooseJurisdictionModal=false">取消</Button>
                          <Button type="primary" @click="getCheckedNodes">保存</Button>
                      </div>
                </Modal>
                <!-- 选择权限的弹出框end -->
                <!-- 编辑弹框start -->
                <Modal v-model="editJurisdictionModal" class="small-modal" title="修改角色名称">
                    
                    <Form ref="editRole" :model="editRole" :rules="ruleValidate" :label-width="80">
                        <FormItem label="角色名称" prop="roleName">
                            <Input v-model="editRole.roleName" size="large" placeholder="角色名称"></Input>
                        </FormItem>

                        <FormItem label="排序">
                          <Select v-model="editRole.sort">
                              <Option :key="item" :value="item" v-for="item in sortList">{{item}}</Option>
                              
                          </Select>
                        </FormItem>
                      
                    </Form>
                    <div slot="footer">
                      <Button @click="editJurisdictionModal=false">取消</Button>
                      <Button type="primary" @click="saveRole('editRole')">保存</Button>
                    </div>
                </Modal>
                <!-- 编辑弹框end -->
            </div>
        </div>
    </div>
</template>

<script>
export default {
  data() {
    return {
      chooseJurisdictionModal: false,
      editJurisdictionModal: false,
      createRoleModal: false,
      selfDefinedRoleList: [],
      functionIds:[],
      selfDefinedRoleListNum: 0,
      sortList:[0,1,2,3,4,5,6,7,8,9],
      jurisdictionTreeData:[],
      roleId:'',
      
      chooseList:[],
      newRole: {
        roleName :'',
        roleType :1,
        sort:''
      },
      editRole:{
        roleName :'',
        roleType :1,
        sort:''
      },
      searchValue: "",
      pageNum: 1,
      pageSize: 9,
      defaultProps: {
        children: "childList",
        label: "functionName"
      },
      ruleValidate: {
      roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
         
      },

      columns7: [
        {
          title: "角色编号",
          key: "roleOrder",
          align: "center",
          width: 150,
          type:'index'
        },
        {
          title: "角色名称",
          key: "roleName",
          align: "center"
        },
        {
          title: "创建人",
          key: "createUserName",
          align: "center",
          render:(h,params)=>{
            if(params.row.createUserName==null){
              return "暂无";
            }else{
              return params.row.createUserName
            }
          }

        },

        {
          title: "创建时间",
          key: "createTime",
          align: "center",
           width: "300",
          render: (h, params) => {
            if (params.row.createTime == null) {
              return "暂无";
            }else{
              return new Date(parseInt(params.row.createTime))
              .toLocaleString()
              .replace(/:\d{1,2}$/, " ");
            }
          }
        },
        {
          title: "操作",
          key: "action",
          width: 350,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    size: "small"
                  },
                  style: {
                    marginRight: "10px"
                  },
                  on: {
                    click: () => {
                      // this.show(params.index)
                      this.chooseJurisdictionModal = true;
                      this.roleId = params.row.roleId;
                      this.getJurisdictionTreeData(params).then((state)=>{
                        this.setCheckedKeys()
                      })
                     
                    }
                  }
                },
                "选择权限"
              ),
              h(
                "Button",
                {
                  props: {
                    size: "small"
                  },
                  style: {
                    marginRight: "10px"
                  },
                  on: {
                    click: () => {
                      // this.show(params.index)
                      this.editJurisdictionModal = true;
                      this.showRoleInfo(params)
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      // this.show(params.index)
                      //this.chooseJurisdictionModal = true;
                     this.getJurisdictionTreeData(params)
                    this.remove(params);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data6: [
        {
          roleOrder: "1",
          roleName: "管理员",
          createPeople: "老习",
          createTime: "2017/10/18"
        },
        {
          roleOrder: "2",
          roleName: "超级管理员",
          createPeople: "老王",
          createTime: "2017/10/14"
        },
        {
          roleOrder: "3",
          roleName: "项目经理",
          createPeople: "老刘",
          createTime: "2017/10/12"
        },
        {
          roleOrder: "4",
          roleName: "董事长",
          createPeople: "老王",
          createTime: "2017/10/16"
        }
      ]
    };
  },
  created() {
    this.getSelfDefinedRoleList(this.pageNum, this.pageSize, "");
  },
  methods: {
    //获取自定义角色列表
    getSelfDefinedRoleList(pageNum, pageSize) {
      this.$ajax
        .post(
          "/api/roleInfo/info/queryRoleListByRoleType",
          `roleType=1&pageNum=${pageNum}&pageSize=${pageSize}&roleName=${this
            .searchValue}`
        )
        .then(response => {
        // console.log(response.data);
          if (response.data.code == 1) {
            this.selfDefinedRoleList = response.data.resdata.list;
            this.selfDefinedRoleListNum = response.data.resdata.total;
          } else {
            this.$Modal.error({
            title: "错误",
            content: response.data.msg
          });
          }
        })
        .catch(error => {
          this.$Modal.error({
            title: "错误",
            content: error
          });
        });
    },
    //搜索查询自定义角色列表
    searchRole() {
      this.getSelfDefinedRoleList(
        this.pageNum,
        this.pageSize,
        this.searchValue
      );
    },
    //根据roleId查询权限数
    getJurisdictionTreeData(params) {
      return new Promise((resolve, reject) => {
      this.$ajax
        .post("/api/role/function/tree", `roleId=${params.row.roleId}`)
        .then(response => {
         // console.log(response.data);
          if (response.data.code == 1) {
            this.jurisdictionTreeData = response.data.resdata.treeList;
            this.chooseList = response.data.resdata.chooseList;
            resolve(true)
            
          } else {
            this.$Modal.error({
              title: "错误",
              content: response.data.msg
            });
          }
        })
        .catch(error => {
          this.$Modal.error({
            title: "错误",
            content: error
          });
        });
      })
    },
    //保存添加新角色
  saveRole(name){
    this.$refs[name].validate((valid) => {
      if(name=='newRole'){
        if (valid) {
          //this.$Message.success('提交成功!');
          this.$ajax.post("/api/roleInfo/info/insertRoleInfo",this.newRole)
          .then(response=>{
            if(response.data.code==1){
             // console.log(response.data)
              this.$Message.success(response.data.msg)
              this.createRoleModal =false;
              this.getSelfDefinedRoleList(this.pageNum, this.pageSize, "");

            }else{
              this.$Modal.error({
                  title: "错误",
                  content: response.data.msg
              });
            }
          }).catch(error=>{
              this.$Modal.error({
                title: "错误",
                content: error
              });
          })
           
        }

      }else if(name=='editRole'){
        if (valid) {
          //this.$Message.success('提交成功!');
          this.$ajax.post("/api/roleInfo/info/updateRoleInfo",this.editRole)
          .then(response=>{
            if(response.data.code==1){
             // console.log(response.data)
              this.$Message.success(response.data.msg)
              this.editJurisdictionModal =false;
              this.getSelfDefinedRoleList(this.pageNum, this.pageSize, "");

            }else{
              this.$Modal.error({
                  title: "错误",
                  content: response.data.msg
              });
            }
          }).catch(error=>{
              this.$Modal.error({
                title: "错误",
                content: error
              });
          })
           
        }

      }
        
     })
  },
  //回显角色信息
  showRoleInfo(params){
    this.$ajax.post("/api/roleInfo/info/queryRoleInfoById",`roleId=${params.row.roleId}`)
    .then(response=>{
      //console.log(response.data)
      if(response.data.code==1){
        this.editRole = response.data.resdata;
      }else{
          this.$Modal.error({
                title: "错误",
                content: response.data.msg
          });
      }
    }).catch(error=>{
        this.$Modal.error({
          title: "错误",
          content: error
        });

    })

  },
  setCheckedKeys(){
       this.$refs.tree.setCheckedKeys(this.chooseList);
    },
  //获取需要提交的权限id
    getCheckedNodes() {
      let getCheckedNodes = this.$refs.tree.getCheckedNodes();
      getCheckedNodes.forEach((item)=> {
        this.functionIds.push(item.functionId);
      });
     
      let str = this.functionIds.join(",")
     // console.log(str)
      //return false;
      this.$ajax.post("/api/role/function/saveRoleFunction",`roleId=${this.roleId}&functionIds=${str}`)
      .then(response=>{
        if(response.data.code==1){
         // console.log(response.data)
         this.$Message.success(response.data.msg);
         this.chooseJurisdictionModal = false;
         this.$refs.tree.setCheckedKeys([]);
         this.functionIds=[]
         this.chooseList=[]
        }else{
          this.functionIds=[]
          this.chooseList=[]
          this.$Modal.error({
            title: "错误",
            content: response.data.msg
          });
        }
      }).catch(error=>{
        this.$Modal.error({
            title: "错误",
            content: error
          });
      })
    },
    remove(params) {
      // this.data6.splice(index, 1);
      this.$Modal.confirm({
        title: "警告",
        content: "<p>确定要删除吗？删除后将无法恢复 !</p>",
        onOk: () => {
          //this.data6.splice(index, 1);
          this.$ajax.post("/api/roleInfo/info/deleteRoleInfo",`roleId=${params.row.roleId}`)
          .then(response=>{
           // console.log(response.data)
            if(response.data.code==1){
              this.$Message.success(response.data.msg);
              this.getSelfDefinedRoleList(this.pageNum, this.pageSize, "");

              
            }else{
              // this.$Modal.error({
              //   title: "错误",
              //   content: response.data.msg
              // });
              this.$Message.error(response.data.msg);
            }

          }).catch(error=>{
            this.$Modal.error({
                title: "错误",
                content: error
            });
          })
          
        },
        onCancel: () => {
          this.$Message.info("点击了取消");
        }
      });
    },
    changePage(data) {
     // console.log(data);
     this.getSelfDefinedRoleList(data, this.pageSize, this.searchValue);
    },
    checkChoose() {}
  }
};
</script>

<style>

</style>
